package com.itheima.web.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import com.itheima.util.JedisUtil;
import com.itheima.util.JwtUtil;
import com.itheima.util.SmsUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/user")
public class UserController {

    //发送短信验证码
    @GetMapping("/sendCode")
    public String sendCode(String telephone){
        //1、随机生成6位验证码
        String smsCode = RandomStringUtils.randomNumeric(6);
        //2、将验证码存入redis 5分钟
        Jedis jedis = JedisUtil.getJedis();
        //expire
        jedis.setex("smsCode_"+telephone,300,smsCode);
        //关闭资源
        jedis.close();
        //3、调用阿里云工具类发送短信验证码
        //SmsUtil.sendSms(telephone,smsCode);
        System.out.println("验证码是："+smsCode);
        return "ok";
    }

    @Autowired
    private UserService userService;

    //登录功能
    @GetMapping("/login")
    public String login(String telephone, String code){
        //1、校验验证码
        //从redis获取系统验证码
        Jedis jedis = JedisUtil.getJedis();
        String smsCode = jedis.get("smsCode_" + telephone);
        if(smsCode==null){
            //验证码过期
            return "0";
        }
        if(!smsCode.equals(code)){
            //输入的验证码错误
            return "0";
        }
        //2、校验手机号是否存在
        User user = userService.findByTelephone(telephone);
        if(user==null){
            return "1";
        }
        //3、用户登录成功，记录用户信息
        user.setPassword(null);
        Map<String, Object> map = BeanUtil.beanToMap(user);
        String token = JwtUtil.createToken(map);

        return token;
    }

    //校验用户登录状态
    @GetMapping("/verify")
    public String verify(@RequestHeader("Authorization") String token){
        //基于jwt工具类校验token
        try {
            Map map = JwtUtil.parseToken(token);
            return "ok";
        } catch (Exception e) {
            e.printStackTrace();
            //token解析失败，token无效
            return "401";
        }
    }

}
